package com.cuckoo.cuckoo_app2.ui.dashboard;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.adapters.DashboadrdPlatformAdpter;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.SiteLinkApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.SiteLinkApi;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.enums.PlatformLoginType;
import com.cuckoo.cuckoo_app2.enums.TokneTypeEnum;
import com.cuckoo.cuckoo_app2.model.IntentResponseModel;
import com.cuckoo.cuckoo_app2.ui.PlatformActivity;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.LocalBroadCodeUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;

import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment {

    private RecyclerView recyclerView;
    private DashboadrdPlatformAdpter adapter;
    private Button buttomTipsAdd;
    private TextView countNumber;
    private List<Platform> dataList = new ArrayList<>();
    private ConstraintLayout constraintLayout;

    /**
     * 通讯回调
     */
    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            Log.i("LocalBroadcastReceiver", action);

            if (action.equals(LocalBroadCodeUtils.LOCAL_BROADCAST_TASK_REFRESH)) {
                IntentResponseModel model = (IntentResponseModel) intent.getSerializableExtra("model");
                switch (model.getCode()) {
                    case LocalBroadCodeUtils.LOCAL_BROADCAST_TASK_REFRESH:
                        getData();
                        updateRecyclerViewData();
                        break;
                }
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i("TEST", "DashboardFragment.onCreate");
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i("TEST", "DashboardFragment.onCreateView");
        return inflater.inflate(R.layout.fragment_dashboard, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.i("TEST", "DashboardFragment.onViewCreated");
        super.onViewCreated(view, savedInstanceState);
        constraintLayout = view.findViewById(R.id.not_data);

        countNumber = view.findViewById(R.id.count_number);
        // 初始化 RecyclerView
        recyclerView = view.findViewById(R.id.recycler_dashboard);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 初始化适配器并设置给 RecyclerView
        adapter = new DashboadrdPlatformAdpter(getContext(), dataList, new ButtonClickListener());
        recyclerView.setAdapter(adapter);

        // 添加按钮
        buttomTipsAdd = view.findViewById(R.id.das_enter);
        buttomTipsAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 跳转添加
                Intent intent = new Intent(getContext(), PlatformActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onStart() {
        Log.i("TEST", "DashboardFragment.onStart");
        super.onStart();

        // 创建数据
        getData();
        updateRecyclerViewData();
    }

    @Override
    public void onResume() {
        Log.i("TEST", "DashboardFragment.onResume");
        super.onResume();

        // 注册BroadcastReceiver以接收广告广播
        IntentFilter intentFilter = new IntentFilter();
        // 跳转登录页面
        intentFilter.addAction(LocalBroadCodeUtils.LOCAL_BROADCAST_TASK_REFRESH);
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        Log.i("TEST", "DashboardFragment.onPause");
        super.onPause();

        // 注销BroadcastReceiver
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    public void onStop() {
        Log.i("TEST", "DashboardFragment.onStop");
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        Log.i("TEST", "DashboardFragment.onDestroyView");
        super.onDestroyView();

    }

    public void getData() {
        PlatformBusiness platformBusiness = new PlatformBusinessImp();
        dataList = platformBusiness.getAll();
        Log.i("TEST", "请求数据：" + dataList.size() + "");
        this.onCountNumber();
        if (dataList.size() > 0) {
            constraintLayout.setVisibility(View.GONE);
        } else {
            constraintLayout.setVisibility(View.VISIBLE);
        }
    }

    public void clearRecyclerViewData() {
        if (adapter != null) {
            adapter.clearData(); // 调用适配器的方法来清空数据
        }
    }

    /**
     * 更新页面
     */
    public void updateRecyclerViewData() {
        if (adapter != null) {
            adapter.updateData(dataList); // 调用适配器的方法来更新数据
        }
    }


    public void onCountNumber() {
        countNumber.setText(String.valueOf(dataList.size()));
    }

    public class ButtonClickListener {
        public void onLoginout(Platform platform) {
            Log.i("TEST", platform.toString());
            PlatformBusiness platformBusiness = new PlatformBusinessImp();
            platform.setStart(0);
            platform.setIsLogin(0);
            platform.setMessag("退出登录");
            platformBusiness.updata(platform);
            getData();

            updateRecyclerViewData();
        }

        public void onLogin(Platform platform) {
            Log.i("TEST", platform.toString());
            // 检测当前是否可用
            User user = MyApplication.getInstances().getUser();
            if (user == null || user.getIsVip() == 0) {
                DialogUtils.showToast(getContext(), "非会员不能操作");
                return;
            }
            // 登录事件 web 登录还是 接口登录
            SiteLinkBusiness siteLinkBusiness = new SiteLinkBusinessImp();
            SiteLink siteLink = siteLinkBusiness.getByID(platform.getId());
            if(siteLink.getTokneType().equals(TokneTypeEnum.TOKEN_TYPE_API)){
                RouteUtils.toPlatformLoginActivity(getContext(), siteLink.getId());
                return;
            }
            RouteUtils.toWebViewActivity(getContext(), platform.getId(), "login");
        }

        public void onStopsin(Platform platform) {
            Log.i("TEST", platform.toString());
            PlatformBusiness platformBusiness = new PlatformBusinessImp();
            platform.setStart(0);
            platform.setMessag("停止接单");
            platformBusiness.updata(platform);
            getData();

            updateRecyclerViewData();
        }

        public void onStartsin(Platform platform) {
            Log.i("TEST", platform.toString());
            // 检测当前是否可用
            User user = MyApplication.getInstances().getUser();
            if (user == null || user.getIsVip() == 0) {
                DialogUtils.showToast(getContext(), "非会员不能操作");
                return;
            }

            PlatformBusiness platformBusiness = new PlatformBusinessImp();
            platform.setStart(1);
            platform.setHasTips(0);
            platform.setMessag("接单中");
            platformBusiness.updata(platform);
            getData();

            updateRecyclerViewData();
        }

        public void onEnter(Platform platform) {
            Log.i("TEST", platform.toString());
            // 检测当前是否可用
            User user = MyApplication.getInstances().getUser();
            if (user == null || user.getIsVip() == 0) {
                DialogUtils.showToast(getContext(), "非会员不能操作");
                return;
            }

            RouteUtils.toWebViewActivity(getContext(), platform.getId(), "enter");
        }

    }

}